package br.com.caelum.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestaInsercao {

	public static void main(final String[] args) throws SQLException {

		try (final Connection connection = new ConnectionPool().getConnection()) {

			connection.setAutoCommit(false);
			final String sql = "insert into Produto (nome, descricao) values (?, ?)";

			try (final PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

				TestaInsercao.adiciona("TV LCD", "32 Polegadas", preparedStatement);
				TestaInsercao.adiciona("BlueRay", "Full HDMI", preparedStatement);
				connection.commit();

			} catch (final Exception e) {
				e.printStackTrace();
				connection.rollback();
				System.out.println("Rollback efetuado");
			}

		}
	}

	private static void adiciona(final String nome, final String descricao, final PreparedStatement preparedStatement) throws SQLException {

		if (nome.equals("BlueRay")) {
			throw new IllegalArgumentException("Problema ocorrido");
		}

		preparedStatement.setString(1, nome);
		preparedStatement.setString(2, descricao);

		final boolean resultado = preparedStatement.execute();
		System.out.println(resultado);

		final ResultSet resultSet = preparedStatement.getGeneratedKeys();

		while (resultSet.next()) {
			final String id = resultSet.getString("id");
			System.out.println(id + " gerado");
		}
		resultSet.close();
	}
}
